package com.online.controller;

import com.alibaba.fastjson.JSONObject;
import com.online.entity.*;
import com.online.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/exam")
public class ExamController {

    @Autowired
    ExamService examService;

    @Autowired
    StudentService studentService;

    @Autowired
    CEService ceService;

    @Autowired
    StudentAnswerService studentAnswerService;

    @Autowired
    PaperService paperService;

    @Autowired
    CourseContactClassService courseContactClassService;

    @Autowired
    StudentClassService studentClassService;

    /**
     * 查询当前登录老师的测试列表
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/showExam", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showTeacherExam(HttpServletRequest httpServletRequest) {

        Subject subject = SecurityUtils.getSubject();
        String teacherNumber = (String) subject.getPrincipal();

        List<Exam> examList = examService.showAllExam(teacherNumber);

        if (!examList.isEmpty()) {
            httpServletRequest.setAttribute("result", examList);
            return "teacher/exam_detail";
        } else {
            httpServletRequest.setAttribute("error", "error");
            return "teacher/exam_detail";
        }
    }

    /**
     * 查询学生的考试列表
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/studentExam", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showStudentExam(HttpServletRequest httpServletRequest) {

        //获取当前登录学生
        Subject subject = SecurityUtils.getSubject();
        String studentNumber = (String) subject.getPrincipal();

        //根据班级信息查询当前学生的试卷,存储在examList
        Student student = studentService.showByStudentNumber(studentNumber);
        String studentClass = student.getStudentClass();
        List<Integer> examList = ceService.showAStudentExam(studentClass);

        for (int i = 0; i < examList.size(); i++) {
            System.out.println(examList.get(i));
        }
        //初始化studentAnswerList存储学生的对应的试卷答案
        List<StudentAnswer> studentAnswerList = new ArrayList<>();

        //根据查询的examId,返回查询的学生的试卷列表
        List<Exam> exams = new ArrayList<>();
        List<StudentAnswer> answerList = new ArrayList<>();

        if (examList.size() != 0) {

            //查询对应的答案
            for (int i = 0; i < examList.size(); i++) {
                exams.add(examService.showAExam(examList.get(i)));
                studentAnswerList = studentAnswerService.showAStudentAnswer(studentNumber, examList.get(i));

                if (studentAnswerList != null) {
                    for (int j = 0; j < studentAnswerList.size(); j++) {
                        answerList.add(studentAnswerList.get(i));
                    }
                }
            }

            for (int i = 0; i < answerList.size(); i++) {
                System.out.println(answerList.get(i).getStudentNumber() + ":" + answerList.get(i).getExamId());
            }

            httpServletRequest.setAttribute("studentNumber", studentNumber);
            httpServletRequest.setAttribute("answerList", answerList);
            httpServletRequest.setAttribute("examList", exams);

            return "student/student_exam_list";
        } else {
            httpServletRequest.setAttribute("result", "暂时没有考试任务!");
            return "student/student_exam_list";
        }
    }

    /**
     * 教师删除一次测试内容
     *
     * @param examId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteExam", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String deleteExam(@RequestParam("examId") Integer examId) {

        //删除测试记录
        int result = examService.deleteARecord(examId);

        //删除测试和班级记录关系
        result = ceService.deleteARecord(examId);

        //删除测试的内容
        List<Paper> paperList = paperService.showPaperByExamId(examId);
        if(!paperList.isEmpty()) {
            result = paperService.deleteARecord(examId);
        }

        List<StudentAnswer> answerList = studentAnswerService.countDeliver(examId);
        if(!answerList.isEmpty()) {
            //删除学生的有关此次测试的答案
            result = studentAnswerService.deleteARecord(examId);
        }

        if (result != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("删除成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "删除失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 教师发布一次考试
     * examType=0为作业，examType=1为考试
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/examAdd", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addAExam(@RequestParam(value = "examName", required = false) String examName,
                           @RequestParam(value = "courseName", required = false) String courseName,
                           @RequestParam(value = "blanksKnowledge", required = false) String blanksKnowledge,
                           @RequestParam(value = "optionsKnowledge", required = false) String optionsKnowledge,
                           @RequestParam(value = "blanksNumber", required = false) Integer blanksNumber,
                           @RequestParam(value = "optionsNumber", required = false) Integer optionsNumber,
                           @RequestParam(value = "examType", required = false) Integer examType,
                           @RequestParam(value = "scoreOptions", required = false) Integer scoreOptions,
                           @RequestParam(value = "scoreBlanks", required = false) Integer scoreBlanks,
                           @RequestParam(value = "studentClass", required = false) String studentClass) {

        Subject subject = SecurityUtils.getSubject();
        String workNumber = (String) subject.getPrincipal();
//
        Integer examId = examService.showExamId(workNumber, examName);
        System.out.println(examId);

        if (examId != null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "试卷命名重复");
            return JSONObject.toJSONString(errorJsonObject);
        }

        Exam exam = new Exam();

        exam.setExamName(examName);
        exam.setTeacherNumber(workNumber);
        exam.setCourseName(courseName);
        exam.setBlanksKnowledge(blanksKnowledge);
        exam.setOptionsKnowledge(optionsKnowledge);
        exam.setBlanksNumber(blanksNumber);
        exam.setOptionsNumber(optionsNumber);
        exam.setExamType(0);
        exam.setScoreOptions(scoreOptions);
        exam.setScoreBlanks(scoreBlanks);

        int result = examService.addAExam(exam);

        result = ceService.addARecord(exam.getExamId(), studentClass);

        if (result != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("添加成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "添加失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 查询老师是否有重复的试卷命名
     *
     * @param examName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showPaper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showExamByName(@RequestParam(value = "examName", required = false) String examName) {

        Subject subject = SecurityUtils.getSubject();
        String workNumber = (String) subject.getPrincipal();

        Integer examId = examService.showExamId(workNumber, examName);
        System.out.println(examId);

        if (examId != null) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(111, "查询失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }

    /**
     * 插入一次课堂测试
     * @param examName
     * @param courseName
     * @param blanksKnowledge
     * @param optionsKnowledge
     * @param blanksNumber
     * @param optionsNumber
     * @param examType
     * @param scoreOptions
     * @param scoreBlanks
     * @param courseId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addTest", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String addATest(@RequestParam(value = "examName", required = false) String examName,
                           @RequestParam(value = "courseName", required = false) String courseName,
                           @RequestParam(value = "blanksKnowledge", required = false) String blanksKnowledge,
                           @RequestParam(value = "optionsKnowledge", required = false) String optionsKnowledge,
                           @RequestParam(value = "blanksNumber", required = false) Integer blanksNumber,
                           @RequestParam(value = "optionsNumber", required = false) Integer optionsNumber,
                           @RequestParam(value = "examType", required = false) Integer examType,
                           @RequestParam(value = "scoreOptions", required = false) Integer scoreOptions,
                           @RequestParam(value = "scoreBlanks", required = false) Integer scoreBlanks,
                           @RequestParam(value = "courseId", required = false) Integer courseId) {

        System.out.println(courseId);
        Subject subject = SecurityUtils.getSubject();
        String workNumber = (String) subject.getPrincipal();

//      根据课程id查询classId
        List<CourseContactClass> classId = courseContactClassService.selectClassId(courseId);

//      根据classId查询className
        List<String> classNameList = new ArrayList<>();
        System.out.println("课程名字" + classNameList.size());
        for(CourseContactClass c : classId ) {
            StudentClass studentClass = studentClassService.showClassDetailById(c.getClassId());
            classNameList.add(studentClass.getClassName());
        }

        Integer examId = examService.showExamId(workNumber,examName);
        System.out.println(examId);

        if (examId != null) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "试卷命名重复");
            return JSONObject.toJSONString(errorJsonObject);
        }

        Exam exam = new Exam();

        exam.setExamName(examName);
        exam.setTeacherNumber(workNumber);
        exam.setCourseName(courseName);
        exam.setBlanksKnowledge(blanksKnowledge);
        exam.setOptionsKnowledge(optionsKnowledge);
        exam.setBlanksNumber(blanksNumber);
        exam.setOptionsNumber(optionsNumber);
        exam.setExamType(0);
        exam.setScoreOptions(scoreOptions);
        exam.setScoreBlanks(scoreBlanks);

        int result = examService.addAExam(exam);

        for(String c : classNameList) {
            System.out.println(c);
            result = ceService.addARecord(exam.getExamId(),c);
        }

        if (result != 0) {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("添加成功");
            return JSONObject.toJSONString(correctJsonObject);
        } else {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "添加失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
    }
}


